package com.android.qjpmc.application_module.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.android.qjpmc.R;
import com.android.qjpmc.application_module.station.fragment.JCAnalogCurveSet;
import com.android.qjpmc.bean.DeviceValueBean;
import com.android.qjpmc.bean.ReportDataDevicesBean;
import com.android.qjpmc.bean.StationDeviceBean;
import com.android.qjpmc.data_module.AnalogDataItem;
import com.android.qjpmc.data_module.PwrDataModule;
import com.android.qjpmc.data_module.PwrDevice;
import com.android.qjpmc.data_module.PwrStation;
import com.android.qjpmc.data_module.PwrStationSet;
import com.android.qjpmc.databinding.ActivityReportDataBinding;
import com.android.qjpmc.databinding.DeviceItemDataBinding;
import com.android.qjpmc.databinding.ItemReportDataItemBinding;
import com.android.qjpmc.databinding.SelectReportValuesBinding;
import com.android.qjpmc.widget.base.BaseCommonActivity;
import com.android.qjpmc.widget.databindingadapter.BaseBindingItemPresenter;
import com.android.qjpmc.widget.databindingadapter.BaseDataBindingDecorator;
import com.android.qjpmc.widget.databindingadapter.SingleTypeBindingAdapter;
import com.android.qjpmc.widget.utils.TimeUtils;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class SelectReportDataActivity extends BaseCommonActivity<ActivityReportDataBinding> implements BaseBindingItemPresenter<Object> {
    int m_SelectDeviceIndex = 0;
    int m_SelectValueIndex = 0;
    String m_start_time;
    String m_end_time;
    int m_station_id;
    int m_device_id;
    int m_analog_id;
    private SingleTypeBindingAdapter adapter;
    JCAnalogCurveSet m_curve_set = new JCAnalogCurveSet();
    PwrStation m_the_power_station = null;

    PwrStation GetThePwrStation()
    {
        return m_the_power_station;
    }

    void SetPwrStation(PwrStation station)
    {
        m_the_power_station = station;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_report_data;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);
        GetTheCurrentTime();
        mBinding.tvTimeStar.setText(m_start_time);
        mBinding.tvTimeEnd.setText(m_end_time);
        ArrayList<String> data_list = new ArrayList<String>();
        data_list.add("日报表");
        data_list.add("月报表");
        data_list.add("年报表");

        //适配器
        ArrayAdapter<String> arr_adapter= new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, data_list);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_list_item_checked);
        //加载适配器
        mBinding.deviceSpinner.setAdapter(arr_adapter);
        IniDeviceList();
        /*
        List<ReportDataDevicesBean> list = new ArrayList<>();
        list.add(new ReportDataDevicesBean("电气柜1", false));
        list.add(new ReportDataDevicesBean("电气柜2", false));
        list.add(new ReportDataDevicesBean("电气柜3", false));

        List<ReportDataDevicesBean> list2 = new ArrayList<>();
        list2.add(new ReportDataDevicesBean("Ua", false));
        list2.add(new ReportDataDevicesBean("Ub", false));

        // 不可嵌套滑动
        mBinding.recyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerView.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleTypeBindingAdapter(this, list, R.layout.device_item_data);
        adapter.setItemPresenter(this);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setItemDecorator((BaseDataBindingDecorator<ReportDataDevicesBean, DeviceItemDataBinding>) (binding, position, viewType, data) -> {
            // 不可嵌套滑动
            binding.itemRecyclerView.setNestedScrollingEnabled(false);
            // 取消head 的 recycleView的焦点
            binding.itemRecyclerView.setFocusableInTouchMode(false);
            //设置布局管理器
            binding.itemRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            SingleTypeBindingAdapter itemAdapter = new SingleTypeBindingAdapter(this, list2, R.layout.item_report_data_item);
            binding.itemRecyclerView.setAdapter(itemAdapter);
            binding.itemRecyclerView.setVisibility(data.isOpen ? View.VISIBLE : View.GONE);
            binding.ivOpen.setRotation(data.isOpen ? 180 : 0);
            binding.tvName.setText(data.name);

            itemAdapter.setItemDecorator((BaseDataBindingDecorator<ReportDataDevicesBean, ItemReportDataItemBinding>) (binding2, position2, viewType2, data2) -> {
                binding2.tvName.setText(data2.name);
            });


        });*/
    }

    TimePickerView pvStartTime;
    TimePickerView pvEndTime;

    public void onSelectStartTime() {
        if (pvStartTime == null) {
            pvStartTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    m_start_time = TimeUtils.getParseDayTextTime(date);
                    mBinding.tvTimeStar.setText(m_start_time);
                }
            }).setType(new boolean[]{true, true, true, true, true, false})
                    .build();
        }
        pvStartTime.show();
    }

    public void onSelectEndTime() {
        if (pvEndTime == null) {
            pvEndTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    m_end_time = TimeUtils.getParseDayTextTime(date);
                    mBinding.tvTimeEnd.setText(m_end_time);
                }
            }).setType(new boolean[]{true, true, true, true, true, false})
                    .build();
        }
        pvEndTime.show();
    }

    @Override
    public void onItemClick(int position, Object itemData) {

    }

    public void OnOK()
    {
        if (m_curve_set.GetCurveCount() == 0)
        {
            AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                    .setTitle("提示")//标题
                    .setMessage("请选择一个数据点！")//内容
                    .setIcon(null)//图标//.setIcon(R.mipmap.ic_launcher)//图标
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                        }
                    })
                    .create();
            alertDialog1.show();
            return;
        }
        PwrDataModule.getInstance().AddReportDataQueryRecord(m_start_time, m_end_time, m_station_id, m_device_id, m_analog_id);
        this.finish();
    }
    public void OnCancel()
    {
        this.finish();
    }
    public void onCheckDevices(int position, ReportDataDevicesBean itemData) {
        itemData.isOpen = !itemData.isOpen;
        adapter.notifyItemChanged(position);
    }
    void IniDeviceList(){

        List<StationDeviceBean> device_bean_list = new ArrayList<>();
        PwrStationSet set = PwrDataModule.getInstance().GetPwrStationSet();
        StationDeviceBean theBean = null;
        PwrStation ThePwrStation = PwrDataModule.getInstance().GetCurrentStationNode();
        SetPwrStation(ThePwrStation);
        if (ThePwrStation != null) {
            mBinding.title.setText("【"+ThePwrStation.getM_Name()+"】" + "请选择报表数据（单选）");
            PwrDevice TheDevice = ThePwrStation.GetFirstDevice();
            while (TheDevice != null) {
                theBean = new StationDeviceBean();//
                theBean.m_ThePwrDevice = TheDevice;
                TheDevice = TheDevice.GetNext();
                device_bean_list.add(theBean);
            }
        }



        m_curve_set.clear();


        // 不可嵌套滑动
        mBinding.recyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerView.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleTypeBindingAdapter(this, device_bean_list, R.layout.select_report_values);
        adapter.setItemPresenter(this);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setItemDecorator((BaseDataBindingDecorator<StationDeviceBean, SelectReportValuesBinding>) (binding, position, viewType, data) -> {
            // 不可嵌套滑动
            binding.itemRecyclerView.setNestedScrollingEnabled(false);
            // 取消head 的 recycleView的焦点
            binding.itemRecyclerView.setFocusableInTouchMode(false);
            //设置布局管理器
            binding.itemRecyclerView.setLayoutManager(new LinearLayoutManager(this));

            ArrayList<DeviceValueBean> ValueList = new ArrayList<DeviceValueBean>();
            StationDeviceBean TheDevice = device_bean_list.get(position);

            DeviceValueBean value_bean = null;
            if (TheDevice != null)
            {
                ArrayList<AnalogDataItem> AnalogList = TheDevice.m_ThePwrDevice.GetAnalogDataList();
                if (AnalogList != null)
                {
                    for (AnalogDataItem item: AnalogList)
                    {
                        value_bean = new DeviceValueBean();
                        if (value_bean != null)
                        {
                            value_bean.m_DataItem = item;
                            ValueList.add(value_bean);
                        }
                    }
                };
            }


            SingleTypeBindingAdapter itemAdapter = new SingleTypeBindingAdapter(this, ValueList, R.layout.item_report_data_item);
            binding.itemRecyclerView.setAdapter(itemAdapter);
            binding.itemRecyclerView.setVisibility(data.isOpen ? View.VISIBLE : View.GONE);
            binding.ivOpen.setRotation(data.isOpen ? 180 : 0);
            if (data.m_ThePwrDevice != null)
            {
                binding.tvName.setText(data.m_ThePwrDevice.getM_Name());
            }

            // binding.
            itemAdapter.setItemDecorator((BaseDataBindingDecorator<DeviceValueBean, ItemReportDataItemBinding>) (binding2, position2, viewType2, the_value) -> {

                if (the_value.m_DataItem != null)
                {
                    binding2.tvName.setText(the_value.m_DataItem.m_Name);
                }
                PwrStation station = GetThePwrStation();
                if (station != null)
                {
                    m_station_id = station.getM_ID();//站ID
                    AnalogDataItem value_item = station.GetAnalogDataItem(position, position2);
                    {
                        if (value_item != null)
                        {
                            if (m_curve_set.IsCurveExist(value_item)  != null)
                            {
                                binding2.checkBox.setChecked(true);
                            }
                            else
                            {
                                binding2.checkBox.setChecked(false);
                            }
                        }
                        else
                        {
                            binding2.checkBox.setChecked(false);
                        }
                    }

                    //for (AnalogDataItem item: AnalogList)


                }
                else
                {
                    binding2.checkBox.setChecked(false);
                }
                binding2.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        m_SelectDeviceIndex = position;
                        m_SelectValueIndex = position2;
                        PwrStation station = GetThePwrStation();
                        if (station != null)
                        {
                            AnalogDataItem value_item = station.GetAnalogDataItem(m_SelectDeviceIndex, m_SelectValueIndex);

                            if (isChecked == true)
                            {
                                if (m_curve_set.GetCurveCount() >= 1)
                                {
                                    AlertDialog alertDialog1 = new AlertDialog.Builder(buttonView.getContext())
                                            .setTitle("提示")//标题
                                            .setMessage("只能选择一个数据点！")//内容
                                            .setIcon(null)//图标//.setIcon(R.mipmap.ic_launcher)//图标
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                    Toast.makeText(buttonView.getContext(), "选择失败", Toast.LENGTH_SHORT).show();
                                                }
                                            })
                                            .create();
                                    alertDialog1.show();
                                    binding2.checkBox.setChecked(false);
                                    return;
                                }
                                PwrDevice device = station.GetPwrDeviceByIndex(m_SelectDeviceIndex);
                                if (device != null)
                                {
                                    m_device_id = device.GetID();
                                }
                                if (value_item != null)
                                {
                                    m_analog_id = m_SelectValueIndex;
                                }

                                m_curve_set.AddCurve(value_item, Color.RED);
                            }
                            else
                            {
                                m_curve_set.RemoveCurve(value_item);
                            }
                        }
                    }
                });

            });


        });
    }
    public void onCheckDevices(int position, StationDeviceBean itemData) {
        itemData.isOpen = !itemData.isOpen;
        adapter.notifyItemChanged(position);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    void GetTheCurrentTime()
    {
        long timecurrentTimeMillis = System.currentTimeMillis();

        long timeGetTime =new Date().getTime();

        long timeSeconds = System.currentTimeMillis();

        long timeMillis = Calendar.getInstance().getTimeInMillis();

        Log.d("test", "  当前时间戳1->:"+timecurrentTimeMillis);

        Log.d("test", "  当前时间戳2->:"+timeGetTime);

        Log.d("test", "  当前时间戳3->:"+timeSeconds);

        Log.d("test", "  当前时间戳4->:"+timeMillis);

        SimpleDateFormat sdf =new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());

        String time1 = sdf.format(timecurrentTimeMillis);

        String time2 = sdf.format(timeGetTime);

        String time3 = sdf.format(timeSeconds);

        String time4 = sdf.format(timeMillis);

        Log.d("test", timecurrentTimeMillis +"  现在的时间1->:" + time1);

        Log.d("test", timeGetTime +"  现在的时间2-->:" + time2);

        Log.d("test", timeSeconds +"  现在的时间2-->:" + time3);

        Log.d("test", timeMillis +"  现在的时间2-->:" + time4);
        m_start_time = time2;
        m_end_time = time2;
    }
}
